package megrez.mail.sender.component.template;


import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.codehaus.groovy.control.CompilationFailedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer;

import groovy.lang.Writable;
import groovy.text.Template;
import megrez.mail.sender.common.MailSenderException;

/**
 * Groovy模板处理
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Component
public class GroovyTemplageProcess implements TemplateProcess {
    @Autowired
    private GroovyMarkupConfigurer configurer;

    @Override
    public String render(String templateValue, Map<String, Object> params) {
        Template template;
        try {
            template = configurer.getTemplateEngine().createTemplate(templateValue);
            Writable writable = template.make(params);
            Writer writer = new StringWriter();
            writable.writeTo(writer);
            return writer.toString();
        } catch (CompilationFailedException | ClassNotFoundException | IOException e) {
            throw new MailSenderException(e);
        }

    }

}
